let app = getApp()

Page({
  data: {
	  release_id: '',
    c_val: 0, // 动态计算进度
    mainServiceValue: -1,
    mainServiceLists: [],
	serviceTypeLists: [
	  { id: 1, name: '按月计算', selected: false,icon: 'icon-month'},
	  { id: 2, name: '按日计算', selected: false ,icon: 'icon-day'},
	  { id: 3, name: '按小时计算', selected: false ,icon: 'icon-hour'},
	],
	serviceTypeValue:0,
    service_type_status: false,
	startTime: '09:00', // 默认开始时间
	endTime: '17:30',   // 默认结束时间
	workYearLists: [
	  { id: 1, name: '不限', selected: false},
	  { id: 2, name: '一年以上', selected: false },
	  { id: 3, name: '一年到三年', selected: false},
	  { id: 4, name: '三年到五年', selected: false},
	  { id: 5, name: '五年以上', selected: false},
	],
	workYearValue:0,
    work_year_status: false,
	zzRequireLists: [
		{ id: 1, name: '不限', selected: false},
		{ id: 2, name: '医疗护理员', selected: false},
		{ id: 3, name: '高级护理员', selected: false },
		{ id: 4, name: '特级护理员', selected: false},
	],
	zzRequireValue: 0,
    zz_require_status: false,
	jsRequireLists: [
		{ id: 1, name: '不限', selected: false},
		{ id: 2, name: '会生活照护', selected: false },
		{ id: 3, name: '会医学技术', selected: false},
		{ id: 4, name: '会中医康养', selected: false},
		{ id: 5, name: '会推拿/拔罐/针灸', selected: false },
		{ id: 6, name: '会医学急救', selected: false},
	],
	jsRequireValue: 0,
    js_require_status: false,
	ageRequireLists: [
		{ id: 1, name: '不限', selected: false},
		// { id: 2, name: '30岁以下', selected: false },
		// { id: 3, name: '35岁以下', selected: false},
		// { id: 4, name: '40岁以下', selected: false },
		// { id: 5, name: '45岁以下', selected: false},
		// { id: 6, name: '50岁以下', selected: false },
		{ id: 7, name: '55岁以下', selected: false},
		// { id: 8, name: '60岁以下', selected: false },
	],
	min_price: 0,
	max_price:0,
	ageRequireValue: 0,
    age_require_status: false,
	selectedAddress: '',
	selectedPhone: '',
	phone: '',
	navigationAddress: '',
	latitude: '',
	longitude: '',
  },
  onLoad: function(options) {
	new app.ToastPannel();
    var that = this;
    that.canvasRing = that.selectComponent("#canvasRing");
    that.canvasRing.showCanvasRing();
	
	var key = wx.getStorageSync('key')
	var uid = wx.getStorageSync('u')
	var id = options.release_id || ''
	if(id) {
		wx.request({
		  url: app.configData.shop.api_url + '/index.php?ctl=Service_Require&met=requireDetail&typ=json',
		  data: { k: key, u: uid, id: id },
		  method: 'GET', 
		  header: {
		    "Content-Type": "application/json"
		  }, // 设置请求的 header
		  success: function (res) {
		    if(res.data.status == 200){
				var require_info = res.data.data.require_detail
				that.setData({
					c_val: 20,
					mainServiceValue: parseInt(require_info.mainServiceValue),
					release_id: id
				})
				that.drawProgress(that.data.c_val)
		    }
		  },
		  fail: function (res) {
		    that.show('数据加载失败')
		  }
		})
	}
	
	
	wx.request({
	  url: app.configData.shop.api_url + '/index.php?ctl=Service_Cat&met=tree&typ=json',
	  data: { k: key, u: uid},
	  method: 'GET', 
	  header: {
	    "Content-Type": "application/json"
	  }, // 设置请求的 header
	  success: function (res) {
	    if(res.data.status == 200){
			that.setData({
				mainServiceLists: res.data.data.items
			})
	    }
	  },
	  fail: function (res) {
	    that.show('数据加载失败')
	  }
	})
  },
  add_address() {
      // 使用 wx.navigateTo 建立事件通道
      wx.navigateTo({
        url: '../address_select/address_select?from=select',
        events: {
          // 定义接收地址的事件监听器
          acceptAddress: (address) => {
            this.setData({ selectedAddress: address })
          },
		  acceptPhone: (phone) => {
		    this.setData({ selectedPhone: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),phone:phone })
		  },
		  acceptNavigationAddress: (navigationAddress) => {
		    this.setData({ navigationAddress: navigationAddress })
		  },
		  acceptLatitude: (latitude) => {
		    this.setData({ latitude: latitude })
		  },
		  acceptLongitude: (longitude) => {
		    this.setData({ longitude: longitude })
		  },
        },
        success: (res) => {
          // 保存事件通道引用
          this.addressChannel = res.eventChannel
        }
      })
    },
  //选择新地址
  address_select: function () {
    wx.redirectTo({
      url: '../address_select/address_select'
    })
  },
  //完善度方法
  drawProgress(){ 
    var that = this;
    that.canvasRing = that.selectComponent("#canvasRing");
    that.canvasRing.showCanvasRing();
  },
  //选择主要服务 单选 切换一级服务
  selectMainService: function(e) {
    const index = e.currentTarget.dataset.index;
	const mainServiceLists = this.data.mainServiceLists.map((item, i) => ({
	    ...item,
	    selected: i === index ? !item.selected : false,
	    children: item.children.map(child => ({
	      ...child,
	      selected: false
	    }))
	}));
	  
    this.setData({
		mainServiceValue: index,
		//清空原本选中的内容
		serviceTypeLists: this.data.serviceTypeLists.map(item => ({ ...item, selected: false })),
		serviceTypeValue: 0,
		service_type_status: false,
		workYearLists: this.data.workYearLists.map(item => ({ ...item, selected: false })),
		workYearValue: 0,
		work_year_status: false,
		zzRequireLists: this.data.zzRequireLists.map(item => ({ ...item, selected: false })),
		zzRequireValue: 0,
		zz_require_status: false,
		jsRequireLists: this.data.jsRequireLists.map(item => ({ ...item, selected: false })),
		jsRequireValue: 0,
		js_require_status: false,
		ageRequireLists: this.data.ageRequireLists.map(item => ({ ...item, selected: false })),
		ageRequireValue: 0,
		age_require_status: false,
		// sliderValue: 6000,// 初始滑块位置
		// priceRange: [6000, 26000],
		max_price: 0
    });
    // console.log(this.data.mainServiceValue)
    //更新完善度
	this.setData({
		c_val: 40
	});
	this.drawProgress(this.data.c_val)
  },
  // 切换一级服务
  toggleMainService: function(e) {
	  
	  
    const index = e.currentTarget.dataset.index;
    const mainServiceLists = this.data.mainServiceLists.map((item, i) => ({
      ...item,
      selected: i === index ? !item.selected : false,
      children: item.children.map(child => ({
        ...child,
        selected: false,
		children: child.children.map(child3 => ({
        ...child3,
        selected: false
      }))
      }))
    }));
    
    this.setData({
      mainServiceLists,
      mainServiceValue: index,
      c_val: 40,
		//清空原本选中的内容
		serviceTypeLists: this.data.serviceTypeLists.map(item => ({ ...item, selected: false })),
		serviceTypeValue: 0,
		service_type_status: false,
		workYearLists: this.data.workYearLists.map(item => ({ ...item, selected: false })),
		workYearValue: 0,
		work_year_status: false,
		zzRequireLists: this.data.zzRequireLists.map(item => ({ ...item, selected: false })),
		zzRequireValue: 0,
		zz_require_status: false,
		jsRequireLists: this.data.jsRequireLists.map(item => ({ ...item, selected: false })),
		jsRequireValue: 0,
		js_require_status: false,
		ageRequireLists: this.data.ageRequireLists.map(item => ({ ...item, selected: false })),
		ageRequireValue: 0,
		age_require_status: false,
		max_price: 0
    });
    
    this.drawProgress();
  },
  // 切换二级服务
  toggleSecondService: function(e) {
    const mainIndex = e.currentTarget.dataset.mainIndex;
    const secondIndex = e.currentTarget.dataset.secondIndex;
    
    const mainServiceLists = [...this.data.mainServiceLists];
	const secondService = mainServiceLists[mainIndex].children[secondIndex];
    // 只修改当前点击的二级服务状态
    secondService.selected = !secondService.selected;
    // 更新三级项目的选中状态（跟随二级服务）
    secondService.children.forEach(child => {
        child.selected = false;
    });
    
    this.setData({
      mainServiceLists,
    });
	this.calculatePrice()
  },
  // 选择三级服务项目
  toggleTagSelection: function(e) {
    const mainIndex = e.currentTarget.dataset.mainIndex;
    const secondIndex = e.currentTarget.dataset.secondIndex;
    const tagIndex = e.currentTarget.dataset.tagIndex;
    
    const mainServiceLists = [...this.data.mainServiceLists];
    const tag = mainServiceLists[mainIndex].children[secondIndex].children[tagIndex];
    
    // 切换选中状态
    tag.selected = !tag.selected;
    
    this.setData({
      mainServiceLists,
    });
	this.calculatePrice()
  },
  // 辅助方法：获取选中的三级标签数量
  getSelectedTagsCount: function() {
    let count = 0;
    this.data.mainServiceLists.forEach(main => {
      main.children.forEach(second => {
        second.children.forEach(tag => {
          if (tag.selected) count++;
        });
      });
    });
    return count;
  },
  
  
  //选择服务项目 单选
  selectTag: function(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
	if(type == 'service_type') {
		const value = this.data.serviceTypeLists[index].name;
		const serviceTypeLists = this.data.serviceTypeLists.map((serviceTypeList, i) => ({
		  ...serviceTypeList,
		  selected: i === index
		}));
		this.setData({
			serviceTypeLists: serviceTypeLists,
			serviceTypeValue: value,
		});
		//只需要增加一次
		if(this.data.service_type_status === false){
			this.setData({
				c_val: this.data.c_val + 20,
				service_type_status: true
			});
		}
		this.calculatePrice();
	} else if(type == 'work_year') {
		const value = this.data.workYearLists[index].name;
		const workYearLists = this.data.workYearLists.map((workYearList, i) => ({
		  ...workYearList,
		  selected: i === index
		}));
		this.setData({
			workYearLists: workYearLists,
			workYearValue: value,
		});
		//只需要增加一次
		if(this.data.work_year_status === false){
			this.setData({
				c_val: this.data.c_val + 10,
				work_year_status: true
			});
		}
		this.calculatePrice();
	} else if(type == 'zz_require') {
		const value = this.data.zzRequireLists[index].name;
		const zzRequireLists = this.data.zzRequireLists.map((zzRequireList, i) => ({
		  ...zzRequireList,
		  selected: i === index
		}));
		this.setData({
			zzRequireLists: zzRequireLists,
			zzRequireValue: value,
		});
		//只需要增加一次
		if(this.data.zz_require_status === false){
			this.setData({
				c_val: this.data.c_val + 10,
				zz_require_status: true
			});
		}
		this.calculatePrice();
	} else if(type == 'js_require') {
		const value = this.data.jsRequireLists[index].name;
		const jsRequireLists = this.data.jsRequireLists.map((jsRequireList, i) => ({
		  ...jsRequireList,
		  selected: i === index
		}));
		this.setData({
			jsRequireLists: jsRequireLists,
			jsRequireValue: value,
		});
		//只需要增加一次
		if(this.data.js_require_status === false){
			this.setData({
				c_val: this.data.c_val + 10,
				js_require_status: true
			});
		}
		this.calculatePrice()
	} else if(type == 'age_require') {
		const value = this.data.ageRequireLists[index].name;
		const ageRequireLists = this.data.ageRequireLists.map((ageRequireList, i) => ({
		  ...ageRequireList,
		  selected: i === index
		}));
		this.setData({
			ageRequireLists: ageRequireLists,
			ageRequireValue: value,
		});
		//只需要增加一次
		if(this.data.age_require_status === false){
			this.setData({
				c_val: this.data.c_val + 10,
				age_require_status: true
			});
		}
	}
    //更新完善度
    this.drawProgress()
  },
  //梳理值
  rakeValue: function(arr,value){
    if (!arr.includes(value)) {
        arr.push(value); // 如果值不存在，则添加
    } else {
        // 如果值存在，则删除
        const index = arr.indexOf(value);
        if (index > -1) {
            arr.splice(index, 1);
        }
    }
    // 输出结果将取决于value的值是否已存在于数组中
    // console.log(arr); 
    return arr;
  },
	// 处理开始时间变化
    bindStartTimeChange: function(e) {
      this.setData({
        startTime: e.detail.value
      });
    },
  
    // 处理结束时间变化
    bindEndTimeChange: function(e) {
      this.setData({
        endTime: e.detail.value
      });
    },
  // 滑动过程中实时更新
    // onSliderChanging: function(e) {
    //   this.setData({
    //     currentPrice: this.calculatePrice(e.detail.value)
    //   });
    // },
	// onSliderChange: function(e) {
 //      // 更新滑块位置
 //      this.setData({
 //        sliderValue: e.detail.value
 //      });
	//   // console.log(e.detail.value)
 //      // 根据滑块位置计算当前价格
 //      let currentPrice = this.calculatePrice(e.detail.value);
 //      // 更新当前价格
 //      this.setData({
 //        currentPrice: currentPrice
 //      });
 //    },
	// calculatePrice: function(sliderValue) {
	// 	let sliderValue2 = sliderValue+2000;
	// 	let currentPrice = sliderValue + '-' + sliderValue2;
	// 	// 四舍五入到两位小数
	// 	return currentPrice;
 //    },
  // 计算总价
  calculatePrice() {
    let that = this
			const key = wx.getStorageSync('key')
			const uid = wx.getStorageSync('u')
			var main_service = that.data.mainServiceLists[that.data.mainServiceValue].cat_id
			// 动态构建 service_contents 数据结构
			let service_contents = {};
			// 遍历所有一级服务分类
			that.data.mainServiceLists.forEach(mainCat => {
				// 为每个一级分类创建一个数组
				let categoryItems = [];
				
				// 遍历一级分类下的二级分类
				mainCat.children.forEach(secondCat => {
				  // 添加二级分类名称到数组
				  if(secondCat.selected) {
					categoryItems.push(secondCat.cat_name);
				  }
				  
				  // 遍历二级分类下的三级标签
				  secondCat.children.forEach(tag => {
					// 添加选中的三级标签到数组
					if (tag.selected) {
					  categoryItems.push(tag.cat_name);
					}
				  });
				});
				
				// 如果该一级分类下有内容，则添加到 service_contents
				if (categoryItems.length > 0) {
				  service_contents[mainCat.cat_name] = categoryItems;
				}
			});
			
			
			var service_type = that.data.serviceTypeValue;
			var work_year = that.data.workYearValue;
			var zz_require = that.data.zzRequireValue;
			var js_require = that.data.jsRequireValue;
			var age_require = that.data.ageRequireValue;
			
			const parme = {
				k: key, 
				u: uid,
				main_service: main_service,
				service_contents: JSON.stringify(service_contents),
				service_type: service_type,
				work_year: work_year,
				zz_require: zz_require,
				js_require: js_require,
				age_require: age_require,
			};
			wx.request({
		    url: app.configData.shop.api_url + '/index.php?ctl=Service_Require&met=getPrice&typ=json',
		    data: parme,
		    method: 'POST', 
		    header: {
		      "Content-Type": "application/x-www-form-urlencoded"
		    }, // 设置请求的 header
		    success: function (res) {
				// console.log(res)
		      if(res.data.status == 200){
		        that.setData({min_price: 0,max_price: res.data.data.price})
		      }
		    },
		    fail: function (res) {
		    
		    }
		  })
	
  },
  
  formSubmit: function (e) {
    let that = this
	if(that.data.c_val !== 100){
		that.show('请完善资料并按要求补充填写完整的内容')
	} else if(that.data.selectedAddress == '') {
		that.show('请按要求补充填写服务地址')
	} else if(that.data.phone == '') {
		that.show('请按要求补充填写联系方式')
	} else {
		const key = wx.getStorageSync('key')
		const uid = wx.getStorageSync('u')
		var id = that.data.release_id
		var main_service = that.data.mainServiceLists[that.data.mainServiceValue].cat_id
		// 动态构建 service_contents 数据结构
		let service_contents = {};
		// 遍历所有一级服务分类
		that.data.mainServiceLists.forEach(mainCat => {
			// 为每个一级分类创建一个数组
			let categoryItems = [];
			
			// 遍历一级分类下的二级分类
			mainCat.children.forEach(secondCat => {
			  // 添加二级分类名称到数组
			  if(secondCat.selected) {
				categoryItems.push(secondCat.cat_name);
			  }
			  
			  // 遍历二级分类下的三级标签
			  secondCat.children.forEach(tag => {
				// 添加选中的三级标签到数组
				if (tag.selected) {
				  categoryItems.push(tag.cat_name);
				}
			  });
			});
			
			// 如果该一级分类下有内容，则添加到 service_contents
			if (categoryItems.length > 0) {
			  service_contents[mainCat.cat_name] = categoryItems;
			}
		});
		var service_type = that.data.serviceTypeValue;
		var start_time = that.data.startTime;
		var end_time = that.data.endTime;
		var work_year = that.data.workYearValue;
		var zz_require = that.data.zzRequireValue;
		var js_require = that.data.jsRequireValue;
		var age_require = that.data.ageRequireValue;
		// var minPrice = e.detail.value.min_price
		// var maxPrice = e.detail.value.max_price
		
		// if(minPrice > maxPrice){
		// 	that.show('最低价格必须小于等于最高价格')
		// }
		
		
		var minPrice = that.data.min_price
		var maxPrice = that.data.max_price
		if(maxPrice <= 0){
			that.show('最低价格必须大于0');return false;
		}
		
		
		const parme = {
			k: key, 
			u: uid,
			id: id,
			main_service: main_service,
			service_contents: JSON.stringify(service_contents),
			service_type: service_type,
			start_time: start_time,
			end_time: end_time,
			work_year: work_year,
			zz_require: zz_require,
			js_require: js_require,
			age_require: age_require,
			min_price: minPrice,
			max_price: maxPrice,
			service_address: that.data.selectedAddress,
			service_phone: that.data.phone,
			navigationAddress: that.data.navigationAddress,
			latitude: that.data.latitude,
			longitude: that.data.longitude
		};
		wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Service_Require&met=addRequire&typ=json',
        data: parme,
        method: 'POST', 
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        }, // 设置请求的 header
        success: function (res) {
          if(res.data.status == 200){
            that.show('发布成功')
            wx.redirectTo({
              url: '../release_list/release_list',
            })
          }else{
            that.show('发布失败')
          }
        },
        fail: function (res) {
        
        }
      })
    }
    
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  
  }
})
